package com.example.service.impl;

import com.example.controller.FileController;
import com.example.service.ContractService;
import com.example.utils.download.DownloadExcelUtil;
import com.example.utils.pdf.ImgUtil;
import com.example.utils.pdf.JavaToPdfHtmlFreeMarker;
import com.example.utils.pdf.PdfKeywordFinder;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @Author runto
 * @Date 2023/10/22 15:21
 * @PackageName:com.example.service.impl
 * @ClassName: contractServiceImpl
 * @Version 1.0
 */
@Service
public class ContractServiceImpl implements ContractService {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    /**
     *
     * @param savePath 存放生成临时文件的路径
     * @param fileName 文件名
     * @param HTML 模板名称
     * @throws Exception
     */
    @Override
    public void saveContract(String savePath, String fileName, String HTML) throws Exception {
        Map<String,Object> data = new HashMap();
        data.put("合同编号","D20230109SDNQB");
        data.put("甲方姓名","熊大");
        data.put("签字日期","2023.01.09");
        //获取静态模板内容
        String content = JavaToPdfHtmlFreeMarker.freeMarkerRender(data,HTML);
        //根据内容生成pdf文件
        JavaToPdfHtmlFreeMarker.createPdf(content,savePath+"/"+fileName);

        //base64字符串,线上通过ResponseBody获取
        String signData = "";
        //给文档添加签名印章
        addSignature(savePath,fileName,signData);
    }

    private void addSignature(String savePath, String fileName,String signData) throws IOException, DocumentException, InterruptedException {
        String oldPdfUrl = savePath +"\\"+ fileName;
        String newPdfUrl = savePath +"\\"+ "1"+fileName;
        //查找签名位置
        float[] position = new float[0];
        PdfReader pdfReader = null;
        PdfStamper pdfStamper = null;
        try {
            position = PdfKeywordFinder.getAddImagePositionXY(oldPdfUrl, "承租人(乙方)签章：");
            //Read file using PdfReader
            pdfReader = new PdfReader(oldPdfUrl);
            pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(newPdfUrl));
            //生成电子签字字节 字节流数组转为图片
            byte[] imgByte = ImgUtil.base64ToImg(signData);
            Image image = Image.getInstance(imgByte);

            //图片缩放
            image.scaleAbsolute(100, 50);
            //绝对位置
            image.setAbsolutePosition(position[1], position[2]-20);
            //页码数
            System.out.println("pages:" + pdfReader.getNumberOfPages());
            PdfContentByte content = pdfStamper.getUnderContent((int) position[0]);
            content.addImage(image);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BadElementException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }finally {
            pdfStamper.close();
            pdfReader.close();
            Thread.sleep(500);
            logger.info("导入---下载---结束,删除文件");
            logger.info("oldPdfUrl" + oldPdfUrl);
            boolean flag = DownloadExcelUtil.deleteFile(oldPdfUrl);
            logger.info("导入---下载---结束,删除文件是否成功：" + flag);
        }
    }
}
